// XML配置文件处理组合式函数

import type { TradingConfiguration } from '@/types/trading'
import { useMonitorManager } from '../useMonitorManager'

export function useXMLConfig() {
  // 自动加载XML配置（默认文件）
  const autoLoadXMLConfiguration = async (openTradingPanel: (setNumber: number, tradeName?: string, contractCode?: string) => Promise<void>) => {
    try {
      // 默认配置文件名
      const defaultFileName = 'td_config.xml'
      // 读取并解析XML配置
      const config = await loadTradingPanelXML(defaultFileName)
      if (config && config.panels && config.panels.length > 0) {
        // 恢复面板配置
        await restorePanelConfiguration(config, openTradingPanel)
      } 
    } catch (error) {
      console.warn('自动加载配置失败，可能是首次启动或配置文件不存在:', error)
      // 自动加载失败时不显示错误消息，因为这是正常情况
    }
  }

  // 手动加载XML配置（保留原有功能）
  const loadXMLConfiguration = async (openTradingPanel: (setNumber: number, tradeName?: string, contractCode?: string) => Promise<void>) => {
    try {
      // 简单的文件名输入对话框（实际项目中可以使用文件选择对话框）
      const fileName = prompt('请输入要加载的XML配置文件名（例如：td_config_2024-01-01T12-00-00.xml）:')

      if (!fileName) {
        return
      }

      // 读取并解析XML配置
      const config = await loadTradingPanelXML(fileName)

      if (config && config.panels && config.panels.length > 0) {
        // 恢复面板配置
        await restorePanelConfiguration(config, openTradingPanel)
      }
    } catch (error) {
      console.error('加载配置失败:', error)
    }
  }

  // 恢复面板配置
  const restorePanelConfiguration = async (
    config: any,
    openTradingPanel: (setNumber: number, tradeName?: string, contractCode?: string, windowConfig?: any, priceTick?: number) => Promise<void>
  ) => {
    try {
      // 获取当前系统显示器信息
      const { matchMonitor: matchMonitorFunc } = useMonitorManager()
      
      // 并行创建所有窗口，减少总体等待时间
      const panelPromises = config.panels.map(async (panelConfig: any, index: number) => {
        try {
          // 创建新的交易面板窗口
          const setNumber = panelConfig.setNumber
          const contractCode = panelConfig.contractCode || panelConfig.title
          const tradeName = contractCode || `交易面板 - 集合${setNumber}`
          // 匹配目标显示器
          const { monitor, method } = await matchMonitorFunc({
            monitorName: panelConfig.monitorName,
            monitorId: panelConfig.monitorId,
            screenNumber: panelConfig.screenNumber
          })

          let finalX, finalY
          if (monitor) {
            // 计算基于目标显示器的绝对坐标
            finalX = monitor.position.x + panelConfig.window.x
            finalY = monitor.position.y + panelConfig.window.y
          } else {
            // 匹配失败，使用主显示器
            finalX = panelConfig.window.x
            finalY = panelConfig.window.y
          }

          // 准备窗口配置，包括位置和显示器信息
          const windowConfig = {
            x: finalX,
            y: finalY,
            width: panelConfig.window.width,
            height: panelConfig.window.height,
            screenNumber: panelConfig.screenNumber || 1, // SC字段，显示器编号
            monitorId: panelConfig.monitorId, // 显示器标识
            monitorName: panelConfig.monitorName, // 显示器名称
            monitorPosition: panelConfig.monitorPosition, // 显示器位置
            monitorSize: panelConfig.monitorSize, // 显示器尺寸
            panelId: panelConfig.id // 使用保存的PID
          }
          // 获取价格间距
          const priceTick = panelConfig.priceTick || 1
          // 立即创建窗口，不等待
          await openTradingPanel(setNumber, tradeName, contractCode, windowConfig, priceTick)
          return { panelId: windowConfig.panelId || `trading-panel-${setNumber}-${Date.now()}`, windowConfig }
        } catch (error) {
          console.error(`恢复面板${panelConfig.setNumber}失败:`, error)
          return null
        }
      })
      
      // 等待所有窗口创建请求完成
      const results = await Promise.all(panelPromises)
      
      // 给窗口一些时间来初始化
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 验证和调整其他显示器上的窗口
      for (const result of results) {
        if (result && result.windowConfig.screenNumber > 1) {
          try {
            const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')
            const createdWindow = await WebviewWindow.getByLabel(result.panelId)
            
            if (createdWindow) {
              // 简化的位置设置，只尝试一次
              try {
                const { LogicalPosition } = await import('@tauri-apps/api/window')
                await createdWindow.setPosition(new LogicalPosition(result.windowConfig.x, result.windowConfig.y))
                await createdWindow.show()
                await createdWindow.setFocus()
              } catch (posError) {
                console.warn(`⚠️ 调整其他显示器窗口位置失败: ${result.panelId}`, posError)
              }
            }
          } catch (error) {
            console.warn(`⚠️ 验证其他显示器窗口失败: ${result.panelId}`, error)
          }
        }
      }
    } catch (error) {
      console.error('恢复面板配置失败:', error)
      throw error
    }
  }

  // 读取XML配置文件（支持从config文件夹读取）
  const loadTradingPanelXML = async (filePath: string) => {
    try {
      const { invoke } = await import('@tauri-apps/api/core')

      let xmlContent: string

      // 如果是相对路径且不包含目录分隔符，尝试从config文件夹读取
      if (!filePath.includes('/') && !filePath.includes('\\')) {
        try {
          xmlContent = await invoke('read_config_file', { filename: filePath }) as string
        } catch (error) {
          xmlContent = await invoke('read_file', { path: filePath }) as string
        }
      } else {
        // 包含路径的情况，直接读取
        xmlContent = await invoke('read_file', { path: filePath }) as string
      }

      // 解析XML内容
      const config = parseXMLConfig(xmlContent)

      return config
    } catch (error) {
      throw error
    }
  }

  // 解析新格式的XML配置文件
  const parseXMLConfig = (xmlContent: string) => {
    // 检查是否是新格式（以<a>标签开头）
    if (xmlContent.includes('<a>') && xmlContent.includes('Title=')) {
      return parseNewFormatXML(xmlContent)
    } else {
      // 使用旧格式解析
      return parseOldFormatXML(xmlContent)
    }
  }

  // 解析新格式XML（用户指定的格式）
  const parseNewFormatXML = (xmlContent: string) => {
    const config = {
      header: {
        version: '1.0',
        timestamp: new Date().toISOString(),
        activeSet: 1,
        totalPanels: 0
      },
      panels: []
    }

    try {
      // 提取所有的a标签（合约面板配置）
      const panelMatches = xmlContent.match(/<a\d+[^>]*\/>/g)
      if (panelMatches) {
        config.panels = panelMatches.map((panelXml, index) => {
          // 提取属性值的辅助函数
          const extractAttribute = (attr: string) => {
            const match = panelXml.match(new RegExp(`${attr}="([^"]*)"`, 'i'))
            return match ? match[1] : ''
          }

          // 从标签名中提取账号信息
          const accountMatch = panelXml.match(/<a(\d+)/)
          const accountNumber = accountMatch ? accountMatch[1] : '93015007'

          const contractCode = extractAttribute('Title')
          const x = parseInt(extractAttribute('X')) || 0
          const y = parseInt(extractAttribute('Y')) || 0
          const width = parseInt(extractAttribute('Width')) || 300
          const height = parseInt(extractAttribute('Height')) || 800
          const rowHeight = parseInt(extractAttribute('RowHeight')) || 16
          const fz = parseInt(extractAttribute('FZ')) || 1
          const zNum = parseInt(extractAttribute('Z_NUM')) || 1
          const yNum = parseInt(extractAttribute('Y_NUM')) || 5
          const ms = extractAttribute('MS') || 'A'
          const sc = parseInt(extractAttribute('SC')) || 1
          const pid = extractAttribute('PID') // 读取保存的PID字段
          const pt = parseFloat(extractAttribute('PT')) || 1 // 读取价格间距PT字段
          const monitorId = extractAttribute('MonitorId') || '' // 显示器标识
          const monitorName = extractAttribute('MonitorName') || '' // 显示器名称

          // 使用保存的PID，如果没有则生成新的
          const panelId = pid || `trading-panel-${sc}-${Date.now() + index}`

          // 从PID中提取集合编号，如果PID存在的话
          let setNumber = sc // 默认使用SC作为集合编号（向后兼容）
          if (pid && pid.includes('trading-panel-')) {
            const pidParts = pid.split('-')
            if (pidParts.length >= 3) {
              const pidSetNumber = parseInt(pidParts[2])
              if (!isNaN(pidSetNumber)) {
                setNumber = pidSetNumber
              }
            }
          }

          return {
            id: panelId,
            setNumber: setNumber,
            screenNumber: sc, // 保存SC作为显示器编号
            monitorId: monitorId, // 显示器标识
            monitorName: monitorName, // 显示器名称
            title: contractCode,
            contractCode: contractCode,
            accountNumber: accountNumber,
            window: {
              x: x,
              y: y,
              width: width,
              height: height,
              visible: true,
              minimized: false,
              maximized: false
            },
            tradingState: {
              currentPrice: 0,
              fontSize: Math.max(8, Math.min(20, Math.floor(rowHeight * 0.8))),
              cellHeight: rowHeight,
              orderType: ms,
              lightOrderQuantity: zNum,
              heavyOrderQuantity: yNum,
              positionMode: 'open',
              cancelMode: 'limited',
              maxCancelOrders: 489,
              currentCancelCount: 0,
              fingerValue: fz
            },
            marketData: {
              totalVolume: 0,
              totalPosition: 0,
              dailyPositionChange: 0,
              priceChangePercent: 0
            },
            priceTick: pt, // 添加价格间距字段
            timestamp: new Date().toISOString()
          }
        })

        config.header.totalPanels = config.panels.length
      }
    } catch (error) {
      console.error('解析新格式XML失败:', error)
    }

    return config
  }

  // 解析旧格式XML（保持兼容性）
  const parseOldFormatXML = (xmlContent: string) => {
    const config = {
      header: {},
      panels: []
    }

    try {
      // 提取Header信息
      const versionMatch = xmlContent.match(/<Version>(.*?)<\/Version>/)
      const timestampMatch = xmlContent.match(/<Timestamp>(.*?)<\/Timestamp>/)
      const activeSetMatch = xmlContent.match(/<ActiveSet>(.*?)<\/ActiveSet>/)
      const totalPanelsMatch = xmlContent.match(/<TotalPanels>(.*?)<\/TotalPanels>/)

      config.header = {
        version: versionMatch ? versionMatch[1] : '1.0',
        timestamp: timestampMatch ? timestampMatch[1] : '',
        activeSet: activeSetMatch ? parseInt(activeSetMatch[1]) : 1,
        totalPanels: totalPanelsMatch ? parseInt(totalPanelsMatch[1]) : 0
      }

      // 提取Panel信息
      const panelMatches = xmlContent.match(/<Panel>[\s\S]*?<\/Panel>/g)
      if (panelMatches) {
        config.panels = panelMatches.map(panelXml => {
          const extractValue = (tag: string) => {
            const match = panelXml.match(new RegExp(`<${tag}>(.*?)<\/${tag}>`))
            return match ? match[1] : ''
          }

          return {
            id: extractValue('ID'),
            setNumber: parseInt(extractValue('SetNumber')),
            title: extractValue('Title'),
            window: {
              x: parseInt(extractValue('X')),
              y: parseInt(extractValue('Y')),
              width: parseInt(extractValue('Width')),
              height: parseInt(extractValue('Height')),
              visible: extractValue('Visible') === 'true',
              minimized: extractValue('Minimized') === 'true',
              maximized: extractValue('Maximized') === 'true'
            },
            tradingState: {
              currentPrice: parseFloat(extractValue('CurrentPrice')),
              fontSize: parseInt(extractValue('FontSize')),
              cellHeight: parseInt(extractValue('CellHeight')),
              orderType: extractValue('OrderType'),
              lightOrderQuantity: parseInt(extractValue('LightOrderQuantity')),
              heavyOrderQuantity: parseInt(extractValue('HeavyOrderQuantity')),
              positionMode: extractValue('PositionMode'),
              cancelMode: extractValue('CancelMode'),
              maxCancelOrders: parseInt(extractValue('MaxCancelOrders')),
              currentCancelCount: parseInt(extractValue('CurrentCancelCount'))
            },
            marketData: {
              totalVolume: parseInt(extractValue('TotalVolume')),
              totalPosition: parseInt(extractValue('TotalPosition')),
              dailyPositionChange: parseInt(extractValue('DailyPositionChange')),
              priceChangePercent: parseFloat(extractValue('PriceChangePercent'))
            },
            timestamp: extractValue('Timestamp')
          }
        })
      }
    } catch (error) {
      console.error('解析旧格式XML配置失败:', error)
    }

    return config
  }

  return {
    autoLoadXMLConfiguration,
    loadXMLConfiguration,
    parseXMLConfig
  }
}
